import React, { Component } from "react";
import MyLink from "../MyLink";
import { reqWheater } from "../../api/index";
import { formateDate } from "../../utils/formateDate";
import memoryUtils from "../../utils/memory";
import storeUtils from "../../utils/storeUtils";
import MenuConfig from "../../config/menuConfig";
import "./index.less";
import { withRouter } from "react-router-dom";
import { Modal } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";

const { confirm } = Modal;
class Header extends Component {
  getWeather = async () => {
    const weather = await reqWheater();
    this.setState({
      CurrentWeather: weather.lives[0],
    });
  };
  state = {
    CurrentWeather: {},
    CurrentTime: formateDate(new Date()),
  };
  showConfirm = () => {
    confirm({
      title: "确定退出系统吗",
      okText: '确认',
    cancelText: '取消',
      icon: <ExclamationCircleOutlined />,
      content: "下次登录需重新输入用户名密码",
      onOk:()=> {
        this.quit()
      },
      onCancel() {
        console.log("Cancel");
      },
    });
  };
  getCurrentTime = () => {
    this.timer = setInterval(() => {
      this.setState({
        CurrentTime: formateDate(new Date()),
      });
    }, 1000);
  };
  quit = () => {
    memoryUtils.user = {};
    storeUtils.removeUser();
    this.props.history.replace("/login");
  };
  getPageTitle = () => {
    const { pathname } = this.props.location;
    MenuConfig.forEach((config) => {
      if (config.key === pathname) {
        this.pageTitle = config.title;
        return;
      } else if (config.children) {
        const cItme = config.children.find((cItem) => cItem.key === pathname);
        if (cItme) {
          this.pageTitle = cItme.title;
          return;
        }
      } else {
        this.pageTitle = "其他页面";
      }
    });
  };
  componentWillUnmount() {
    clearInterval(this.timer);
  }
  componentDidMount() {
    this.getWeather();
    this.getCurrentTime();
    this.getPageTitle();
  }
  render() {
    this.getPageTitle();
    const { city, temperature, weather } = this.state.CurrentWeather;
    const { CurrentTime } = this.state;

    return (
      <div className="header">
        <div className="header_top">
          欢迎，{memoryUtils.user.username}
          <MyLink onClick={this.showConfirm}> 退出</MyLink>
        </div>
        <div className="header_bottom">
          <div className="header_title">{this.pageTitle}</div>
          <div className="header_info">
            <span>{CurrentTime}</span>
            <span className="weather">{`${city},${weather},${temperature}°`}</span>
          </div>
        </div>
      </div>
    );
  }
}
export default withRouter(Header);
